//
//  FriendListTableViewController.m
//  环信即时通讯
//
//  Created by 夏阳光 on 16/4/19.
//  Copyright © 2016年 夏阳光. All rights reserved.
//

#import "FriendListTableViewController.h"
#import <HyphenateFullSDK/EMSDKFull.h>
#import "FriendListTableViewCell.h"
#import "EaseMessageViewController.h"//单聊基础界面
#import "ChatViewController.h"//单聊chat界面

@interface FriendListTableViewController ()<EMContactManagerDelegate>
{
    NSMutableArray* _nameArr;//接收好友列表
}

@end

@implementation FriendListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"我的好友";
    self.tableView.backgroundColor=[UIColor whiteColor];
    _nameArr=[[NSMutableArray alloc]init];
    
    [self getFridendListAndReloadTableView];//获取好友列表并刷新tableView
    
    //注册好友回调
    [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:nil];
}

//获取好友列表并刷新tableView
-(void)getFridendListAndReloadTableView
{
    //获取好友列表
    EMError *error = nil;
    NSArray *userlist = [[EMClient sharedClient].contactManager getContactsFromServerWithError:&error];
    if (!error) {
        NSLog(@"好友获取成功 -- %@",userlist);
        
        [_nameArr removeAllObjects];
        [_nameArr addObjectsFromArray:userlist];
        [self.tableView reloadData];
    }
}


#pragma mark - 监听添加好友回调
//监听回调
/*!
 *  用户A发送加用户B为好友的申请，用户B会收到这个回调
 *
 *  @param aUsername   用户名
 *  @param aMessage    附属信息
 */
- (void)didReceiveFriendInvitationFromUsername:(NSString *)aUsername
                                       message:(NSString *)aMessage
{
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"收到来自%@的请求", aUsername] message:aMessage preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction * acceptAction = [UIAlertAction actionWithTitle:@"好" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action)
    {
    
        // 同意好友请求的方法
        EMError *agreeError = [[EMClient sharedClient].contactManager acceptInvitationForUsername:aUsername];
        if (!agreeError) {
            NSLog(@"发送同意成功");
            
            [self getFridendListAndReloadTableView];//获取好友列表并刷新tableView
        }
    }];
    
    UIAlertAction * rejectAction = [UIAlertAction actionWithTitle:@"NO" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
        // 拒绝好友请求的方法
        EMError *rejectError = [[EMClient sharedClient].contactManager declineInvitationForUsername:aUsername];
        if (!rejectError) {
            NSLog(@"发送拒绝成功");
        }
    }];
    
    [alertController addAction:acceptAction];
    [alertController addAction:rejectAction];
    [self showDetailViewController:alertController sender:nil];
}

//好友申请处理结果回调
//监听回调
- (void)didReceiveAgreedFromUsername:(NSString *)aUsername
{
    NSLog(@"%@同意了我的好友请求",aUsername);
    
    [self getFridendListAndReloadTableView];//获取好友列表并刷新tableView
}
- (void)didReceiveDeclinedFromUsername:(NSString *)aUsername
{
    NSLog(@"%@拒绝了我的好友请求",aUsername);
}




#pragma mark -
- (IBAction)exitAction:(UIBarButtonItem *)sender {
    
    //退出登录
    EMError *error = [[EMClient sharedClient] logout:YES];
    if (!error) {
        NSLog(@"退出成功");
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }else{
        NSLog(@"退出失败");
    }
    
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _nameArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FriendListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FriendListTableViewCell" forIndexPath:indexPath];
    
    NSString* username=_nameArr[indexPath.row];
    cell.nameLabel.text=username;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    //创建聊天会话,传递用户或群id和会话类型(EMConversationType)
//    EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:_nameArr[indexPath.row] conversationType:EMConversationTypeChat];
//    chatController.title=_nameArr[indexPath.row];
//    [self.navigationController pushViewController:chatController animated:YES];

    
    //创建聊天会话,传递用户或群id和会话类型(EMConversationType)
    ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:_nameArr[indexPath.row] conversationType:EMConversationTypeChat];
    chatController.title=_nameArr[indexPath.row];
    [self.navigationController pushViewController:chatController animated:YES];

}







/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
